<?php
declare(strict_types = 1);

namespace app\common\model\mysql;

use think\Model;

class Category extends Model
{
    protected $name = 'mall_category';

    protected $pk = 'id';

    //用户状态
    const STATUS_NORMAL = 1;
    const STATUS_PEDDING = 0;
    const STATUS_DELETE = 99;

    static $statusArr = [
        self::STATUS_NORMAL => '正常',
        self::STATUS_PEDDING => '待审核',
        self::STATUS_DELETE => '删除',
    ];

    protected $autoWriteTimestamp = true;

    public function findCategoryByname($name)
    {
        if (empty($name)) {
            return false;
        }

        $where = [
            'name' => trim($name),
        ];

        return $this->where($where)->find();
    }

    public function getNormalCategorys($field = '*')
    {
        $where = [
            'status' => self::STATUS_NORMAL
        ];

        $order = [
            'listorder' => 'desc',
            'id' => 'desc',
        ];

        return $this->where($where)->field($field)->order($order)->select();
    }

    public function getNormalByPid($pid, $field)
    {
        $where = [
            'pid' => $pid,
            'status' => self::STATUS_NORMAL
        ];

        $order = [
            'listorder' => 'desc',
            'id' => 'desc',
        ];

        return $this->where($where)->field($field)->order($order)->select();

    }


    public function getLists($where, $num = 10)
    {
        $order = [
            'listorder' => 'desc',
            'id' => 'desc',
        ];
        $result = $this->where('status', '<>', self::STATUS_DELETE)
            ->where($where)
            ->order($order)
            ->paginate($num);
        return $result;
    }

    public function updateById($id, $data)
    {
        $data['update_time'] = time();
        return $this->where(['id' => $id])->save($data);
    }

    public function getChildCountInPids($data)
    {
        $where[] = ['pid','in',$data['pid']];
        $where[] = ['status','<>',self::STATUS_DELETE];

        $res = $this->where($where)
            ->field(['pid', 'count(*) as count'])
            ->group('pid')
            ->select();
       // echo $this->getLastSql();exit;
        return $res;
    }
}
